/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 17, 2012  9:05:34 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.mm.outbound
 * File Name : PsProjDefService.java
 * TODO
 */
package sap.business.mm.outbound;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import jpa.entitys.synchro.staging.PsProjDef;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.PsProjDefServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class PsProjDefService {
	
	private static final Logger log = Logger.getLogger(PsProjDefService.class);
	private EntityManager emSynchro;
	private PsProjDefServices psProjDefServices;
	
	/**
	 * 
	 */
	public PsProjDefService() {
		try {
			
			this.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	private void UpdateStagingWhenError(List<PsProjDef> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			psProjDefServices= new PsProjDefServices(this.emSynchro);
			if(!CommonService.IsNull(value_list)){
				List<PsProjDef> newlst = new ArrayList<PsProjDef>();
				for(PsProjDef model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new PsProjDefServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void CreatedSync(List<PsProjDef> value_list, Connection jco_conn) throws Exception  {		
		try{
			
			String sap_bapi = "ZIN_PSMAS_PROJECT";
			String sap_table = "PROJ_DATA";
			psProjDefServices= new PsProjDefServices(this.emSynchro);
			
			JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
			JCoTable table = jco_conn.getTables(sap_table);
			if(!table.isEmpty())
				log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");		
					
			if(!CommonService.IsNull(value_list)){
				log.info("value_list.size : " + value_list.size());			
				log.info("table.getNumRows : " + table.getNumRows());
				
				for (PsProjDef model : value_list) 
		        {								
					table.appendRow();
					table.setValue("VERNR", model.getProjectManagerId());
					table.setValue("VERNA", model.getProjectManagerName());
					table.setValue("ASTNR", "");
					table.setValue("PLFAZ", model.getProjectStartDate());
					table.setValue("PLSEZ", model.getProjectEndDate());
					table.setValue("WERKS", model.getSapPlantCode());
					table.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
					
					log.info("InstanceNo = " + model.getInstanceNo());
		        }
			}	
			
			jcoFunction.execute(jco_conn.getJCoConnection());
			
			List<PsProjDef> lst_r = new ArrayList<PsProjDef>();		
			JCoTable table_r = jco_conn.getTables("RETURN");
			log.info("table_r getNumRows = " + table_r.getNumRows());
			if(!table_r.isEmpty()){
				
				for(int i = 0; i < table_r.getNumRows(); i++)
				{
					table_r.setRow(i);			
					//log.info("PROMIS_TXN_ID = " + table_r.getString("PROMIS_TXN_ID"));
					//log.info("MSG_CODE = " + table_r.getString("MSG_CODE"));
					//log.info("MSG_DESC = " + table_r.getString("MSG_DESC"));
					//log.info("MSG_ALT_DESC = " + table_r.getString("MSG_ALT_DESC"));
					//log.info("MSG_ACTION_RESULT = " + table_r.getString("MSG_ACTION_RESULT"));
					
					PsProjDef model = psProjDefServices.findById(CommonService.IsNullRNull(table_r.getString("PROMIS_TXN_ID")));
					CommonJCOReturn.toString(table_r);
					if(model != null){
						model.setMsgCode(CommonService.IsNullRNull(table_r.getString("MSG_CODE")));
						model.setMsgDesc(CommonService.IsNullRNull(table_r.getString("MSG_DESC")));
						model.setMsgAltDesc(CommonService.IsNullRNull(table_r.getString("MSG_ALT_DESC")));
						model.setMsgActResult(CommonService.IsNullRNull(table_r.getString("MSG_ACTION_RESULT")));
						model.setIsactive("Y");
						model.setIssync("Y");
						
						lst_r.add(model);
					}
				}
				
				psProjDefServices.Updated(lst_r);
				
			}else 
				log.info("isEmpty");
		
		}catch(Exception e){
			
			UpdateStagingWhenError(value_list, e);
			
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
			throw e;
		}finally{
			psProjDefServices = null;
		}
	}
	
	/**
	 * 
	 * @param lst
	 * @throws Exception
	 */
	public void SendingToSAP(List<PsProjDef> lst) throws Exception {
		try{

			if(CommonService.getSize(lst) > 0){
				Connection jco_conn = new Connection();
				
				//ZIN_PSMAS_PROJECT
				//jco_sap_conn.CreatedJCOConnectionProperty();
				//jco_sap_conn.TestedConnectUsingPool();
				//jco_sap_conn.TestedConnectUsingWithOutPool();
				//jco_sap_conn.JcoTestCompany();
				//this.psProjDefServices = new PsProjDefServices(this.emSynchro);
				
				new PsProjDefService().CreatedSync(lst, jco_conn);
			}
		}catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	
//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		try {
//			
//			Connection jco_conn = new Connection();
//			
//			//ZIN_PSMAS_PROJECT
//			
//			
//			//jco_sap_conn.CreatedJCOConnectionProperty();
//			
//			//jco_sap_conn.TestedConnectUsingPool();
//			//jco_sap_conn.TestedConnectUsingWithOutPool();
//			
//			//jco_sap_conn.JcoTestCompany();
//			PsProjDefService  xx = new PsProjDefService();
//						
//			psProjDefServices = new PsProjDefServices(PsProjDefService.emSynchro);
//			List<PsProjDef> lst = psProjDefServices.findIsSync("N");
//			
//			xx.CreatedSync(lst, jco_conn);
//			
//		} catch (Exception e) {
//			log.info(e);
//			e.printStackTrace();
//		}
//
//	}

}
